package com.xja.seckill.rowbackorder.rabbitmq;

import com.rabbitmq.client.Channel;
import com.xja.seckill.order.domain.model.Order;
import com.xja.seckill.order.domain.model.OrderDetail;
import com.xja.seckill.service.OrderDetailService;
import com.xja.seckill.service.OrderService;
import com.xja.seckill.service.SkuService;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@RabbitListener(queues = "death-queue")
public class DeathQueueListener {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private SkuService skuService;

    @Autowired
    private RedisTemplate redisTemplate;


    @RabbitHandler
    public void DeathQueue(@Payload Order order, Channel channel) throws IOException {
        Order orders = orderService.selectByOrderId (order.getId ());
//        System.out.println (orders.toString ());
        Long increment = redisTemplate.opsForValue ().increment ("productCount-1", 1);
        System.out.println (increment);
//        Object o =redisTemplate.opsForValue ().get ("orderId"+order.getId());
//        System.out.println (o);
        if (orders.getStatus ()==1) {
            //库存回滚
            OrderDetail orderDetail = orderDetailService.selectById (orders.getId ());
            Integer skuId = orderDetail.getSkuId ();
            skuService.rollBackCount (skuId);
        }
    }
}
